import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
// 路由Index.ts
/* Router Modules */
import { useUserStoreHook } from '@/store/modules/user'
import { AppRouteType } from './types'
import { Menu } from '@/api/auth/types'
import systemRouter from "@/router/modules/system"
const Layout = () => import('@/views/layout/index.vue')


/**
 * constantRoutes
 * 不需要权限校验的页面
 */
export const constantRoutes: AppRouteType[] = [
  {
    // 当从login界面登录后就会跳转到这个界面上,跳转路径根据path: '/redirect/:path(.*)',
    /**
     * 这样的路由配置通常用于处理动态重定向，当访问/redirect路径时，会加载Layout组件，
     * 并且根据子路由的配置动态加载对应的组件。子路由中的动态参数:path(.*)
     * 可以捕获后面的路径作为参数传递给组件，实现灵活的路由跳转和加载。
     * 确保路由配置和组件路径都是正确的，以便路由能够正常工作。
     */
    path: '/redirect',
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue'),
        meta: { hidden: true }
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    meta: { hidden: true }
  },
  {
    path: '/:pathMatch(.*)*', // TODO: 解决路由爆[Vue Router warn]: No match found for location with path
    component: () => import('@/views/error/404.vue'),
    meta: { hidden: true }
  },
  {
    // 定义这个一级菜单对应的页面，在path: 'dashboard',
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: '首页',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'dashboard', affix: true }
      },
      {
        path: '/404',
        name: '404',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404', hidden: true }
      },
      {
        path: '/401',
        name: '401',
        component: () => import('@/views/error/index.vue'),
        meta: { title: '401', hidden: true }
      },
      {
        path: '/403',
        name: '403',
        component: () => import('@/views/error/index.vue'),
        meta: { title: '403', hidden: true }
      },
      {
        path: '/500',
        name: '500',
        component: () => import('@/views/error/index.vue'),
        meta: { title: '500', hidden: true }
      }
    ]
  }
]


/**
 * 创建路由
 */
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 })
})

/**
 * 重置路由
 */
export const resetRouter = () => {
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && constantRoutes.find((item) => item.name !== name)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export function resetRouter2() {
  router.replace({ path: '/login' })
  // const newRouter = router as any;
  // (router as any).matcher = (newRouter as any).matcher // reset router
}

export default router
